package com.wengzw.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Controller
public class FileUploadController {


    @RequestMapping("/fileupload")
    public String handleformupload(@RequestParam("name") String name,
                                   @RequestParam("uploadfile") List<MultipartFile> uploadfile,
                                   HttpServletRequest request) {
        if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
            for (MultipartFile file : uploadfile) {
                String originame = file.getOriginalFilename();
                //设置上传文件的保存地址目录
                String dirpath = request.getServletContext().getRealPath("/upload/");
                File filepath = new File(dirpath);
                if (!filepath.exists()) {
                    filepath.mkdirs();
                }
                //创建一个新的文件名称，避免重复
                String newFilename = name+"_"+ UUID.randomUUID()+"_"+originame;
                //上传到指定位置
                try {
                    file.transferTo(new File(dirpath + newFilename));
                    System.out.println(filepath + newFilename);
                } catch (IOException e) {
                    e.printStackTrace();
                    return "error";
                }
            }
            return "success";
        }
       else{
           return "error";
        }

    }
}
